//
//  GKZYUniversityDetailController.m
//  GKZYAid
//
//  Created by Tony Zhang on 16/3/11.
//  Copyright © 2016年 GKZYAid. All rights reserved.
//

#import "GKZYUniversityDetailController.h"
#import "GKZYUniversityDetailTopView.h"
#import "MyDefine.h"
#import "GKZYSortLeftBarButtonItemView.h"
#import "MajorButtonView.h"
#import "Urls.h"
#import <AFNetworking.h>
#import "GKZYUniversityModel.h"
#import "GKZYUniversityInfoModel.h"
#import "GKZYUniversityInfoCell.h"
#import "GKYUniversityAcceptModel.h"
#import "GKZYUniversityMajorModel.h"
#import "GKZYUniversityAcceptHeaderView.h"
#import "GKZYUniversityAcceptTalbeViewCell.h"
#import "GKZYUserSortDataHandel.h"
#import "MBProgressHUD.h"

//Tag  值  2000开始

@interface GKZYUniversityDetailController ()<UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate>{

    MBProgressHUD *HUD;
}

//头视图
@property(nonatomic,strong)GKZYUniversityDetailTopView *topView;
//学校介绍按钮
@property(nonatomic,strong)MajorButtonView *introduce;
//学校录取按钮
@property(nonatomic,strong)MajorButtonView *accept;

//切换tableview的scroll
@property(nonatomic,strong)UIScrollView *scroll;

#pragma mark +++++++++++   学校介绍   +++++++++++++++
//学校介绍tableview
@property(nonatomic,strong)UITableView *detailTableView;
//学校简介model
@property(nonatomic,strong)GKZYUniversityInfoModel *infoModel;

#pragma mark +++++++++++++   录取    +++++++++++++++
//录取tableview
@property(nonatomic,strong)UITableView *acceptTableView;
@property(nonatomic,strong)GKYUniversityAcceptModel *acceptModel;
@property(nonatomic,strong)NSMutableArray *dataArray;

@end


@implementation GKZYUniversityDetailController

-(void)loadView{

    [super loadView];
    self.introduce = [[MajorButtonView alloc]initWithFrame:CGRectMake(0, VCHEIGHT/3, VCWIDTH/2, 40)];
    [self.introduce setTheTitle:@"学校简介"];
    self.introduce.backgroundColor = [UIColor whiteColor];
    [self.introduce setTheTitleColor:[UIColor orangeColor] andMarkColor:[UIColor orangeColor]];
    [self.view addSubview:self.introduce];
    
    self.accept = [[MajorButtonView alloc]initWithFrame:CGRectMake(VCWIDTH/2, VCHEIGHT/3, VCWIDTH/2, 40)];
    [self.accept setTheTitleColor:[UIColor colorWithWhite:0.1 alpha:0.5] andMarkColor:[UIColor clearColor]];
    [self.accept setTheTitle:@"录取情况"];
    self.accept.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.accept];
    
    //添加手势
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(introduceTB)];
    [self.introduce addGestureRecognizer:tap1];
    
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(acceptTB)];
    [self.accept addGestureRecognizer:tap2];
    
    self.scroll =[ [UIScrollView alloc]initWithFrame:CGRectMake(0, VCHEIGHT/3+45, VCWIDTH, VCHEIGHT*2/3-45)];
    self.scroll.contentSize = CGSizeMake(VCWIDTH*2, 0);
    self.scroll.delegate = self;
    self.scroll.tag = 2000;
    self.scroll.pagingEnabled = YES;
    [self.view addSubview:self.scroll];
    
    self.detailTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, VCWIDTH, VCHEIGHT*2/3-45)style:(UITableViewStylePlain)];
    self.detailTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.detailTableView.showsVerticalScrollIndicator = NO;
    self.detailTableView.tag = 2001;
    self.detailTableView.dataSource = self;
    self.detailTableView.delegate = self;
    [self.scroll addSubview:self.detailTableView];
    
    self.acceptTableView = [[UITableView alloc]initWithFrame:CGRectMake(VCWIDTH, 0, VCWIDTH, VCHEIGHT*2/3-45)style:(UITableViewStyleGrouped)];
    self.acceptTableView.delegate = self;
    self.acceptTableView.dataSource = self;
    self.acceptTableView.showsVerticalScrollIndicator = NO;
    self.acceptTableView.tag = 2002;
    [self.scroll addSubview:self.acceptTableView];
    [self makeData0];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.alpha = 0;
    self.view.backgroundColor = CustomGrayColor;
}

-(void)viewDidLoad{

    [super viewDidLoad];
    GKZYSortLeftBarButtonItemView *leftBBI = [[GKZYSortLeftBarButtonItemView alloc]initWithFrame:CGRectMake(0, 0, 60, 30)];
    UITapGestureRecognizer *tap3 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(back)];
    [leftBBI addGestureRecognizer:tap3];
    UIBarButtonItem *bar = [[UIBarButtonItem alloc]initWithCustomView:leftBBI];
    self.navigationItem.leftBarButtonItem = bar;
    [self makeData1];
    [self makeData2];
}

#pragma mark +++++++++++++++       解析数据       +++++++++++++++++

-(void)makeData0{
    
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
    HUD.dimBackground = YES;
    HUD.labelText = @"请稍等";
    [HUD showAnimated:YES whileExecutingBlock:^{
        [self dataRequest0];
    } completionBlock:^{
        
        [HUD removeFromSuperview];
        HUD = nil;
    }];
}

-(void)makeData1{

    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
    HUD.dimBackground = YES;
    HUD.labelText = @"请稍等";
    [HUD showAnimated:YES whileExecutingBlock:^{
        [self dataRequest1];
    } completionBlock:^{
        
        [HUD removeFromSuperview];
        HUD = nil;
    }];
}


-(void)makeData2{
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
    HUD.dimBackground = YES;
    HUD.labelText = @"请稍等";
    [HUD showAnimated:YES whileExecutingBlock:^{
        [self dataRequest2];
    } completionBlock:^{
        
        [HUD removeFromSuperview];
        HUD = nil;
    }];
}

-(void)dataRequest0{

    AFHTTPSessionManager  *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", @"text/plain", nil];
    NSDictionary *parameters = @{@"wl":SINGLETON.wl,@"loc_name":SINGLETON.loc_name,@"score":SINGLETON.score,@"sch_id":self.sch_id};
    [manager GET:KschoolDetailUrl parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        
        NSDictionary *dcit = responseObject[@"data"];
        GKZYUniversityModel *model = [[GKZYUniversityModel alloc]init];
        [model setValuesForKeysWithDictionary:dcit];
        self.topView = [[GKZYUniversityDetailTopView alloc]initWithFrame:CGRectMake(0, 0, VCWIDTH, VCHEIGHT/3)];
        [self.topView configureTheViewWithModel:model];
        [self.view addSubview:self.topView];
        
        GKZYSortLeftBarButtonItemView *back = [[GKZYSortLeftBarButtonItemView alloc]initWithFrame:CGRectMake(16, 28, 60, 30)];
        [back setTitleColor:[UIColor whiteColor] andImage:[UIImage imageNamed:@"10enter-my@3x"]];
        UITapGestureRecognizer *tap4 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(back)];
        [back addGestureRecognizer:tap4];
        [self.view addSubview:back];
        self.navigationItem.title = model.sch_name;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"网络连接失败，错误代码：%@",error);
    }];
}


-(void)dataRequest1{
    
    AFHTTPSessionManager  *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", @"text/plain", nil];
    
    NSDictionary *parameters = @{@"wl":SINGLETON.wl,@"loc_name":SINGLETON.loc_name,@"score":SINGLETON.score,@"sch_id":self.sch_id};
    [manager GET:KschoolInfoUrl parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary *dict = responseObject[@"data"];
        self.infoModel = [[GKZYUniversityInfoModel alloc]init];
        [self.infoModel setValuesForKeysWithDictionary:dict];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.detailTableView reloadData];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"网络连接失败，错误代码：%@",error);
    }];
}


-(void)dataRequest2{
    
    AFHTTPSessionManager  *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", @"text/plain", nil];
    NSDictionary *parameters = @{@"wl":SINGLETON.wl,@"loc_name":SINGLETON.loc_name,@"score":SINGLETON.score,@"sch_id":self.sch_id};
    
    [manager GET:KacceptUrl parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        
        NSDictionary *dict = responseObject[@"data"];
        self.acceptModel  = [[GKYUniversityAcceptModel alloc]init];
        [self.acceptModel setValuesForKeysWithDictionary:dict];
        
        self.dataArray = [[NSMutableArray alloc]init];
        for (NSDictionary *dictionary in dict[@"major_list"]) {
            GKZYUniversityMajorModel *model = [[GKZYUniversityMajorModel alloc]init];
            [model setValuesForKeysWithDictionary:dictionary];
            [self.dataArray addObject:model];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.acceptTableView reloadData];
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"网络连接失败，错误代码：%@",error);
    }];
}


#pragma mark ++++++++++++   tap手势事件       +++++++++++++++++

-(void)back{
  
    self.navigationController.navigationBar.alpha = 1;
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)introduceTB{
    
    [self.accept setTheTitleColor:[UIColor colorWithWhite:0.1 alpha:0.5] andMarkColor:[UIColor clearColor]];
    [self.introduce setTheTitleColor:[UIColor orangeColor] andMarkColor:[UIColor orangeColor]];
    
    self.scroll.contentOffset = CGPointMake(0, 0);
}

-(void)acceptTB{
    
    [self.introduce setTheTitleColor:[UIColor colorWithWhite:0.1 alpha:0.5] andMarkColor:[UIColor clearColor]];
    [self.accept setTheTitleColor:[UIColor orangeColor] andMarkColor:[UIColor orangeColor]];
    
    self.scroll.contentOffset = CGPointMake(VCWIDTH, 0);
}

#pragma mark ++++++++++++    scrollView代理方法    ++++++++++++++++++

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    if (scrollView.tag == 2000 ) {
        
        if (scrollView.contentOffset.x == 0) {
            
            [self.accept setTheTitleColor:[UIColor colorWithWhite:0.1 alpha:0.5] andMarkColor:[UIColor clearColor]];
            [self.introduce setTheTitleColor:[UIColor orangeColor] andMarkColor:[UIColor orangeColor]];
            
        }else if (scrollView.contentOffset.x == VCWIDTH){
            
            [self.introduce setTheTitleColor:[UIColor colorWithWhite:0.1 alpha:0.5] andMarkColor:[UIColor clearColor]];
            [self.accept setTheTitleColor:[UIColor orangeColor] andMarkColor:[UIColor orangeColor]];
        }
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    CGFloat origin = scrollView.contentOffset.y;
            if (origin >= VCHEIGHT/3-64) {
                self.introduce.frame = CGRectMake(0, 64, VCWIDTH/2, 40);
                self.accept.frame = CGRectMake(VCWIDTH/2, 64, VCWIDTH/2, 40);
                self.navigationController.navigationBar.alpha = 1;
                self.topView.frame = CGRectMake(0, -VCHEIGHT/3+64, VCWIDTH, VCHEIGHT/3);
                self.topView.imageView.frame = CGRectMake(0, 0, VCWIDTH, VCHEIGHT/3);
                self.scroll.frame = CGRectMake(0, 109, VCWIDTH, VCHEIGHT-109);
                self.detailTableView.frame = CGRectMake(0, 0, VCWIDTH, CGRectGetHeight(self.scroll.frame));
                self.acceptTableView.frame = CGRectMake(VCWIDTH, 0, VCWIDTH, CGRectGetHeight(self.scroll.frame));
            }else if(origin < 0){
                self.topView.frame = CGRectMake(0, 0, VCWIDTH, VCHEIGHT/3);
                self.topView.imageView.frame = CGRectMake(origin, origin, VCWIDTH-2*origin, VCHEIGHT/3-2*origin);
                self.scroll.frame = CGRectMake(0, VCHEIGHT/3+45-origin, VCWIDTH, VCHEIGHT-109);
                self.introduce.frame = CGRectMake(0, VCHEIGHT/3-origin, VCWIDTH/2, 40);
                self.accept.frame = CGRectMake(VCWIDTH/2, VCHEIGHT/3-origin, VCWIDTH/2, 40);
                
            }else{
                self.navigationController.navigationBar.alpha = 0;
                self.introduce.frame = CGRectMake(0, VCHEIGHT/3-origin, VCWIDTH/2, 40);
                self.accept.frame = CGRectMake(VCWIDTH/2, VCHEIGHT/3-origin, VCWIDTH/2, 40);
                
                self.topView.frame = CGRectMake(0, -origin, VCWIDTH, VCHEIGHT/3);
                self.scroll.frame = CGRectMake(0, VCHEIGHT/3 +45-origin, VCWIDTH, VCHEIGHT *2/3 -45+origin);
                self.detailTableView.frame = CGRectMake(0, 0, VCWIDTH, CGRectGetHeight(self.scroll.frame));
                self.acceptTableView.frame = CGRectMake(VCWIDTH, 0, VCWIDTH, CGRectGetHeight(self.scroll.frame));
    }
}


#pragma mark ++++++++++    tableView代理方法   +++++++++++++

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    switch (tableView.tag) {
        case 2001:{
            return 1;
        }
            break;
        default:{
            return self.dataArray.count;
        }
            break;
    }
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (tableView.tag == 2002 && self.acceptModel != nil) {
       
        GKZYUniversityAcceptHeaderView *headerView = [[GKZYUniversityAcceptHeaderView alloc]initWithFrame:CGRectMake(0, 0, KmainScreenBoundsWidth, 500)];
            [headerView configureTheViewWithModel:self.acceptModel];
        headerView.backgroundColor = [UIColor whiteColor];
            return headerView;
    }
    return nil;
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (tableView.tag == 2002) {
        return 500 ;
    }
    return 0.1;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [self tableView:tableView cellForRowAtIndexPath:indexPath].frame.size.height;
    
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (tableView.tag == 2001) {
        
        GKZYUniversityInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (cell == nil) {
            cell = [[GKZYUniversityInfoCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"cell"];
        }
        if (self.infoModel != nil) {
            
            [cell configureTheCellWithModel:self.infoModel];
            [cell.explandBut addTarget:self action:@selector(refreshTheCell) forControlEvents:(UIControlEventTouchUpInside)];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
        }
        return cell;
    }else{
    
        GKZYUniversityAcceptTalbeViewCell *cell = [[GKZYUniversityAcceptTalbeViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"acceptCell"];
        GKZYUniversityMajorModel *model = self.dataArray[indexPath.row];
        NSArray *aray = model.score_list;
        NSMutableArray *dataArray = [[NSMutableArray alloc]init];
        
        for (NSDictionary *dict in aray) {
            
            NSString *string = dict[@"avg_score"];
            [dataArray addObject:string];
        }
      
       [cell configureTheCellWithMajorName:model.major_name AndDataArray:dataArray];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}


-(void)refreshTheCell{

    self.infoModel.explainOrPick = !self.infoModel.explainOrPick;
    [self.detailTableView reloadData];

}


@end
